import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
// 获取用户 api
import { getUserProfile, getUserDataById } from '@/api/user.js'
const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  // 设置 token
  SET_TOKEN: (state, token) => {
    state.token = token
    // 持久 存储 token
    setToken(token)
  },
  // 移出 token
  REMOVE_TOKEN(state) {
    state.token = null
    // 移出 token
    removeToken()
  },
  // 设置用户名信息
  SET_USERINFO(state, userInfo) {
    state.userInfo = userInfo
  },
  // 移除用户名信息
  REMOVE_USERINFO(state) {
    state.userInfo = {}
  },

  // -------------------模板自带的-------------------------------
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // 在 vuex 中发送请求
  async userLogin(context, obj) {
    // 调用 ajax
    const res = await login(obj)
    context.commit('SET_TOKEN', res.data)
  },
  // 封装发起用户名请求函数
  async getUserInfo({ commit }) {
    // 调用 获取用户信息 api
    const res = await getUserProfile()
    // 获取用户头像
    const file = await getUserDataById(res.data.userId)
    // 把上边获取的两份合并在一起，保存到vuex中
    commit('SET_USERINFO', { ...res.data, ...file.data })
    // 当前用户可以看到的菜单 res.data.roles.menus
    return res.data.roles.menus
  },
  // 退出登录
  userLoginut({ commit }) {
    // 移出用户信息
    commit('REMOVE_USERINFO')
    // 清空 token
    commit('REMOVE_TOKEN')
    // 重置路由
    resetRouter()
  },

  // -------------------模板自带的-------------------------------
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo)
        .then(response => {
          commit('SET_TOKEN', response.data)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { data } = response

          if (!data) {
            return reject('Verification failed, please Login again.')
          }

          const { name, avatar } = data

          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken() // must remove  token  first
          resetRouter()
          commit('RESET_STATE')
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
